package api

import (
	"gateway/basic/config"
	user "gateway/basic/proto/userproto"
	"gateway/handler/request"
	"gateway/handler/response"
	"github.com/gin-gonic/gin"
	"strconv"
)

// CreateWithdrawal
// @Summary      创建提现申请
// @Description  用户提交提现申请
// @Tags         提现模块
// @Accept       json
// @Produce      json
// @Param        withdrawal  body      request.CreateWithdrawalReq  true  "提现信息"
// @Success      200  {object}  response.Response
// @Failure      400   {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /withdrawal/create [post]
func CreateWithdrawal(c *gin.Context) {
	var req request.CreateWithdrawalReq
	if err := c.ShouldBind(&req); err != nil {
		response.SrvError(c, "参数格式错误", err.Error())
		return
	}

	userId := c.GetUint("userId")

	// TODO: 验证支付密码

	// 调用user服务创建提现申请
	res, err := config.UserClient.CreateWithdrawal(c, &user.CreateWithdrawalReq{
		UserId:        uint64(userId),
		Amount:        req.Amount,
		AccountType:   int32(req.AccountType),
		AccountNumber: req.AccountNumber,
		AccountName:   req.AccountName,
		BankName:      req.BankName,
	})
	if err != nil {
		response.SrvError(c, "创建提现申请失败", err)
		return
	}
	response.Success(c, "提现申请提交成功", res)
}

// GetWithdrawalList
// @Summary      获取提现记录列表
// @Description  获取当前用户的提现记录列表
// @Tags         提现模块
// @Accept       json
// @Produce      json
// @Param        page  query      int  false  "页码"
// @Param        page_size  query      int  false  "每页数量"
// @Success      200  {object}  response.Response
// @Failure      400   {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /withdrawal/list [get]
func GetWithdrawalList(c *gin.Context) {
	var req request.GetWithdrawalListReq
	if err := c.ShouldBind(&req); err != nil {
		req.Page = 1
		req.PageSize = 10
	}

	userId := c.GetUint("userId")

	res, err := config.UserClient.GetWithdrawalList(c, &user.GetWithdrawalListReq{
		UserId:   uint64(userId),
		Page:     int32(req.Page),
		PageSize: int32(req.PageSize),
	})
	if err != nil {
		response.SrvError(c, "获取提现记录失败", err)
		return
	}
	response.Success(c, "查询成功", res)
}

// GetWithdrawalDetail
// @Summary      获取提现详情
// @Description  获取提现申请详情
// @Tags         提现模块
// @Accept       json
// @Produce      json
// @Param        id  query      int  true  "提现ID"
// @Success      200  {object}  response.Response
// @Failure      400   {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /withdrawal/detail [get]
func GetWithdrawalDetail(c *gin.Context) {
	idStr := c.Query("id")
	id, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		response.SrvError(c, "参数错误", err)
		return
	}

	res, err := config.UserClient.GetWithdrawalDetailG(c, &user.GetWithdrawalDetailReq{
		Id: id,
	})
	if err != nil {
		response.SrvError(c, "获取提现详情失败", err)
		return
	}
	response.Success(c, "查询成功", res)
}

// AuditWithdrawal
// @Summary      审核提现申请
// @Description  管理员审核用户的提现申请
// @Tags         提现模块
// @Accept       json
// @Produce      json
// @Param        audit  body      request.AuditWithdrawalReq  true  "审核信息"
// @Success      200  {object}  response.Response
// @Failure      400   {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /withdrawal/audit [post]
func AuditWithdrawal(c *gin.Context) {
	var req request.AuditWithdrawalReq
	if err := c.ShouldBind(&req); err != nil {
		response.SrvError(c, "参数格式错误", err.Error())
		return
	}

	auditorId := c.GetUint("userId")

	res, err := config.UserClient.AuditWithdrawalG(c, &user.AuditWithdrawalReq{
		Id:        req.ID,
		AuditorId: uint64(auditorId),
		Status:    int32(req.Status),
		Reason:    req.Reason,
	})

	if err != nil {
		response.SrvError(c, "审核失败", err)
		return
	}
	response.Success(c, "审核成功", res)
}

// GetWithdrawalConfig
// @Summary      获取提现配置信息
// @Description  获取提现金额限制等信息
// @Tags         提现模块
// @Accept       json
// @Produce      json
// @Success      200  {object}  response.Response
// @Failure      400   {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /withdrawal/config [get]
func GetWithdrawalConfig(c *gin.Context) {
	config := map[string]interface{}{
		"min_amount":       100,
		"max_amount":       50000,
		"daily_max_amount": 100000,
		"fee_rate":         0.005,
		"min_fee":          2,
	}
	response.Success(c, "查询成功", config)
}

// GetWithdrawalSumAmount 提现金额聚合统计接口
// @Summary      提现金额统计面板
// @Description  获取提现金额的时间区间聚合统计，支持按日/月/年分组
// @Tags         提现模块
// @Accept       json
// @Produce      json
// @Param        start_time  query   string  false  "统计开始时间，格式：2024-01-01 或 2024-01-01 00:00:00"
// @Param        end_time    query   string  false  "统计结束时间，格式：2024-01-31 或 2024-01-31 23:59:59"
// @Param        group_type  query   int     false  "分组方式：1=按日 2=按月 3=按年，默认1"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /withdrawal/amount_panel [get]
func GetWithdrawalSumAmount(c *gin.Context) {
	start := c.Query("start_time")
	end := c.Query("end_time")
	
	// 参数验证：如果提供了开始时间或结束时间，两者都必须提供
	if (start != "" && end == "") || (start == "" && end != "") {
		response.SrvError(c, "参数错误", "开始时间和结束时间必须同时提供")
		return
	}

	// 解析分组类型，默认为1（按日）
	groupTypeStr := c.DefaultQuery("group_type", "1")
	groupType, err := strconv.Atoi(groupTypeStr)
	if err != nil || groupType < 1 || groupType > 3 {
		response.SrvError(c, "参数错误", "分组类型无效，仅支持1(按日)/2(按月)/3(按年)")
		return
	}

	// 调用gRPC服务
	resp, err := config.UserClient.SumWithdrawalAmount(c, &user.SumWithdrawalAmountReq{
		StartTime: start,
		EndTime:   end,
		Type:      int32(groupType),
	})
	
	if err != nil {
		response.SrvError(c, "提现统计失败", err)
		return
	}

	response.Success(c, "统计成功", resp)
}
